package com.zs.usc.common;

import com.zs.usc.constant.Global;
import com.zs.usc.utils.RedisUtils;
import com.zs.usc.vo.CurrentUserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Zero
 * @description 当前登录用户信息
 * @date 2021/11/15 10:37
 */
public class BaseAuthController {

    private static final ThreadLocal<CurrentUserInfo> context = new ThreadLocal<>();

    @Autowired
    RedisUtils redisUtil;

    protected String getToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader(Global.AUTHORIZE_TOKEN);
        return token;
    }

    protected CurrentUserInfo getCurrentUser() {
        CurrentUserInfo u = BaseAuthController.get();
        if (u == null) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String token = request.getHeader(Global.AUTHORIZE_TOKEN);
            if (StringUtils.isEmpty(token)) {
                token = request.getParameter(Global.AUTHORIZE_TOKEN);
            }
            String objStr = redisUtil.getStr(token);
            if (objStr != null) {
//                u = JsonUtils.string2Obj(objStr, User.class);
//                BaseController.set(u);
            }
        }
        return u;
    }

    /**
     * 设置用户信息
     *
     * @param loginInfo -- 用户信息
     */
    public static void set(CurrentUserInfo loginInfo) {
        context.set(loginInfo);
    }

    /**
     * 获取用户信息
     *
     * @return -- 用户信息
     */
    public static CurrentUserInfo get() {
        return context.get();
    }

    /**
     * 移除用户信息
     */
    public static void remove() {
        context.remove();
    }
}
